//
//  RealmManager.m
//  flutter
//
//  Created by GilesZhou on 2020/6/29.
//  Copyright © 2020 Ganee. All rights reserved.
//

#import "RealmManager.h"

@implementation RealmManager
/// 写入缓存中
+ (void)writeData:(RLMObject *)data {
    
    dispatch_queue_t queue = dispatch_queue_create("RealmWriteQueue", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(queue, ^{
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm transactionWithBlock:^{
            [realm addObject:data];
        }];
    });
    
    NSLog(@"realm保存路径------%@", NSHomeDirectory());
}


/// 查询realm中数据
+ (RLMResults *)searchDataWithRealm:(RLMRealm *)realm  Type:(RealmSaveType)type {
    Class class = NSClassFromString(RealmSaveTypeFromString(type));
    RLMResults *results = [class allObjectsInRealm:realm];
    
    return results;
}

/// 查询缓存中数据
+ (RLMResults *)searchDataWithType:(RealmSaveType)type {
    return [RealmManager searchDataWithRealm:[RLMRealm defaultRealm] Type:type];
}

/// 删除缓存中单条记录
+ (void)deleteData:(RLMObject *)data {
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm transactionWithBlock:^{
        [realm deleteObject:data];
    }];
}

/// 删除缓存中多条数据
+ (void)deleteResults:(RLMResults *)results {
    RLMRealm *realm = [RLMRealm defaultRealm];
    for (RLMObject *data in results) {
        [realm transactionWithBlock:^{
            [realm deleteObject:data];
        }];
    }
}

///删除缓存中表中所有的数据
+ (void)deleteAllData {
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm transactionWithBlock:^{
        [realm deleteAllObjects];
    }];
}


#pragma mark - 读取本地realm
/// 读取本地realm中数据
+ (RLMResults *)readLocalRealmWithType:(RealmSaveType)type {
    NSURL *url = [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"RLM" ofType:@"realm"]];
    RLMRealm *realm = [RLMRealm realmWithURL:url];
    
    return [RealmManager searchDataWithRealm:realm Type:type];
}


NSString * const RealmSaveTypeFromString(RealmSaveType type) {
    switch (type) {
        case RealmSaveTypeCrash:
            return @"RealmCrashModel";
            break;
            
        default:
            return @"";
            break;
    }
}

@end
